<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>角色菜单管理</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>
<body>
<h3 class="mb-4">角色菜单管理</h3>

<!-- 搜索框 -->
<div class="search-group">
    <input type="number" id="search" class="form-control" placeholder="请输入角色ID">
    <button class="btn btn-primary" onclick="search()">搜索</button>
    <div class="page-size-selector">
        <span>每页显示:</span>
        <select id="pageSize" class="form-control" onchange="changePageSize()">
            <option value="5">5条</option>
            <option value="10">10条</option>
            <option value="20">20条</option>
            <option value="50">50条</option>
        </select>
    </div>
</div>

<!-- 表格 -->
<table class="table table-bordered align-middle text-center">
    <thead class="table-primary">
    <tr>
        <th>ID</th><th>角色ID</th><th>菜单ID</th><th>操作</th>
    </tr>
    </thead>
    <tbody id="data-body"></tbody>
</table>

<!-- 分页区域 -->
<div class="pagination" id="pagination"></div>

<script>
    let currentPage = 1;
    let currentPageSize = 5;
    let currentRoleId = '';

    function loadData(page = 1, roleId = '') {
        currentPage = page;

        $.ajax({
            url: '/roleMenu/list',
            type: 'GET',
            data: {
                roleId: roleId || undefined,
                page: page,
                size: currentPageSize
            },
            success: function (response) {
                const data = response.data;
                const total = response.total;
                const totalPages = response.totalPages;

                const rows = data.map(item => `
                    <tr>
                        <td>${item.id}</td>
                        <td><input type="number" value="${item.roleId}" data-id="${item.id}" class="form-control roleId" readonly /></td>
                        <td><input type="number" value="${item.menuId}" data-id="${item.id}" class="form-control menuId" readonly /></td>
                        <td>
                            <button class="btn btn-edit btn-sm" onclick="toggleEdit(this, ${item.id})">编辑</button>
                            <button class="btn btn-delete btn-sm" onclick="remove(${item.id})">删除</button>
                        </td>
                    </tr>
                `).join('');
                $('#data-body').html(rows);

                // 生成分页按钮
                let pageButtons = '';
                if (totalPages > 1) {
                    // Previous button
                    pageButtons += `<button ${currentPage === 1 ? 'disabled' : ''} onclick="loadData(${currentPage - 1}, '${currentRoleId}')">上一页</button>`;

                    // Page numbers
                    const startPage = Math.max(1, currentPage - 2);
                    const endPage = Math.min(totalPages, currentPage + 2);

                    if (startPage > 1) {
                        pageButtons += `<button onclick="loadData(1, '${currentRoleId}')">1</button>`;
                        if (startPage > 2) {
                            pageButtons += `<span>...</span>`;
                        }
                    }

                    for (let i = startPage; i <= endPage; i++) {
                        pageButtons += `<button ${i === currentPage ? 'disabled' : ''} onclick="loadData(${i}, '${currentRoleId}')">${i}</button>`;
                    }

                    if (endPage < totalPages) {
                        if (endPage < totalPages - 1) {
                            pageButtons += `<span>...</span>`;
                        }
                        pageButtons += `<button onclick="loadData(${totalPages}, '${currentRoleId}')">${totalPages}</button>`;
                    }

                    // Next button
                    pageButtons += `<button ${currentPage === totalPages ? 'disabled' : ''} onclick="loadData(${currentPage + 1}, '${currentRoleId}')">下一页</button>`;
                }

                // Add total count info
                pageButtons += `<span style="margin-left: 15px;">共 ${total} 条记录</span>`;

                $('#pagination').html(pageButtons);
            },
            error: function () {
                alert("数据加载失败");
            }
        });
    }

    function search() {
        const roleId = $('#search').val().trim();
        currentRoleId = roleId;
        loadData(1, currentRoleId);
    }

    function changePageSize() {
        currentPageSize = parseInt($('#pageSize').val());
        loadData(1, currentRoleId);
    }

    function toggleEdit(btn, id) {
        const isEditing = $(btn).text() === '保存';
        const roleInput = $(`.roleId[data-id=${id}]`);
        const menuInput = $(`.menuId[data-id=${id}]`);

        if (isEditing) {
            update(id);
            roleInput.prop('readonly', true);
            menuInput.prop('readonly', true);
            $(btn).text('编辑').removeClass('btn-primary').addClass('btn-edit');
        } else {
            roleInput.prop('readonly', false);
            menuInput.prop('readonly', false);
            $(btn).text('保存').removeClass('btn-edit').addClass('btn-primary');
        }
    }

    function update(id) {
        const roleId = $(`.roleId[data-id=${id}]`).val();
        const menuId = $(`.menuId[data-id=${id}]`).val();

        if (!roleId || !menuId) {
            alert("角色ID和菜单ID不能为空");
            return;
        }

        $.ajax({
            url: '/roleMenu/update',
            type: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify({ id, roleId, menuId }),
            success: () => {
                loadData(currentPage, currentRoleId);
            },
            error: () => {
                alert("更新失败");
            }
        });
    }

    function remove(id) {
        if (!confirm("确定要删除这条记录吗？")) {
            return;
        }

        $.ajax({
            url: `/roleMenu/delete/${id}`,
            type: 'DELETE',
            success: () => {
                loadData(currentPage, currentRoleId);
            },
            error: () => {
                alert("删除失败");
            }
        });
    }

    $(document).ready(function () {
        loadData(); // 初始加载第一页
    });
</script>
</body>
</html>